package org.dreamwork.hyacinth;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2010-4-25
 * Time: 23:36:10
 */
public class MailManager {
    private String smtpServer;
    private int smtpPort = 25;
    private String protocol = "smtp";
    private String userName;
    private String password;
    private boolean needAuth;

    private static Map<String, MailManager> pools = new ConcurrentHashMap<String, MailManager> ();

    public static String PROP_SMTP_HOST = "mail.smtp.host";
    public static String PROP_SMTP_PORT = "mail.smtp.port";
    public static String PROP_SMTP_AUTH = "mail.smtp.auth";
    public static String PROP_TRANSPORT_PROTOCOL = "mail.transport.protocol";

    private MailManager () {}

    public static MailManager getMailManager (String name) {
        MailManager manager = pools.get (name);
        if (manager == null) {
            manager = new MailManager ();
            pools.put (name, manager);
        }
        return manager;
    }

    public String getSmtpServer () {
        return smtpServer;
    }

    public void setSmtpServer (String smtpServer) {
        this.smtpServer = smtpServer;
    }

    public String getUserName () {
        return userName;
    }

    public void setUserName (String userName) {
        this.userName = userName;
    }

    public String getPassword () {
        return password;
    }

    public void setPassword (String password) {
        this.password = password;
    }

    public boolean isNeedAuth () {
        return needAuth;
    }

    public void setNeedAuth (boolean needAuth) {
        this.needAuth = needAuth;
    }

    public int getSmtpPort () {
        return smtpPort;
    }

    public void setSmtpPort (int smtpPort) {
        this.smtpPort = smtpPort;
    }

    public String getProtocol () {
        return protocol;
    }

    public void setProtocol (String protocol) {
        this.protocol = protocol;
    }

    public Session getSession () {
        Properties props = new Properties ();
        props.put (PROP_SMTP_HOST, smtpServer);
        props.put (PROP_SMTP_PORT, String.valueOf (smtpPort));
        props.put (PROP_TRANSPORT_PROTOCOL, protocol);

        Authenticator auth = null;
        if (needAuth) {
            props.put (PROP_SMTP_AUTH, "true");
            auth = new PasswordAuthenticator (userName, password);
        }

        if (auth != null)
            return Session.getInstance (props, auth);
        return Session.getInstance (props);
    }

    public void send (Mail mail) throws IOException, MessagingException {
        Session session = getSession ();
        if (mail.isDebug ()) session.setDebug (true);
        Transport.send (mail.buildMessage (session));
    }
}